package com.bestv.search.management.datasyn;

import com.bestv.search.common.dataSource.DataSourceKey;
import com.bestv.search.common.dataSource.DataSourceKeyUtil;
import com.bestv.search.common.model.BizType;
import com.bestv.search.common.model.Info;
import com.bestv.search.common.util.CharUtil;
import com.bestv.search.common.util.ChineseCharToEn;
import com.bestv.search.common.util.ScheduleUtil;

import java.io.File;
import java.io.FileFilter;
import java.util.List;
import java.util.Map;

/**
 * @author Michael Wang
 */
public class LocalFileScheduleSyncer extends ProgramSyncerImpl {

    String siteCode = null;
    int validTime = 48;
    String localPath = null;

    public LocalFileScheduleSyncer() {
    }

    public LocalFileScheduleSyncer(Map<String, String> p) throws Exception {
        this.setProps(p);
        justDoIt();
    }

    @Override
    public boolean init(Map<String, String> properties) {
        if (props.get("path") == null || props.get("path").length() == 0) {
            logger.error("Local schedule path is empty!");
            result = false;
            return false;
        } else {
            localPath = props.get("path");
        }
        if (props.get("validTime") != null && props.get("validTime").length() > 0) {
            validTime = Integer.valueOf(props.get("validTime"));
        }
        siteCode = props.get("branch").toUpperCase();
        return true;
    }

    @Override
    public boolean updateProgram() throws Exception {
        logger.info("now read from local schedule file and update to search's");

        /* invalid the overdue schedules */
        DataSourceKey dsKey = DataSourceKeyUtil.convert(siteCode);
        List<Info> overdueSchedules = vm.getOverdueSchedule(dsKey, validTime);
        for (Info overdueSchedule : overdueSchedules) {
            overdueSchedule.setUpdateFlag(2);
        }
        vm.saveUpdateInfoList(dsKey, overdueSchedules);

        File scheduleDir = new File(localPath);
        if (!scheduleDir.exists() || !scheduleDir.isDirectory())
            return false;

        File[] scheduleFiles = scheduleDir.listFiles(new FileFilter() {
            public boolean accept(File pathname) {
                return ".xls".equalsIgnoreCase(pathname.getName().substring(pathname.getName().lastIndexOf(".")));
            }
        });
        for (int i = 0; i < scheduleFiles.length; i++) {
            File scheduleFile = scheduleFiles[i];
            try {
                List<Info> scheduleList = ScheduleUtil.scheduleExcelFileToList(scheduleFile, cm, siteCode);
                BizType bizType = bm.getBizTypeByName(dsKey, "节目单");
                if (bizType == null) {
                    bizType = new BizType();
                    bizType.setPtype("节目单");
                    bm.saveBizTypes(dsKey, bizType);
                }
                for (Info info : scheduleList) {
                    String scheduleName = info.getName();
                    String abbreviation = ChineseCharToEn.getAllFirstLetter(scheduleName);
                    String splitTokens = splitToken(scheduleName);
                    info.setNamePY(abbreviation + " " + CharUtil.charToNum(abbreviation) + " " + splitTokens);

                    info.setP_type("节目单");
                    info.setBizType(bm.getBizTypeByName(dsKey, "节目单"));
                    info.setHitCount(0);
                }
                vm.saveUpdateInfoList(dsKey, scheduleList);
            } catch (Exception e) {
                logger.error("Schedule file " + scheduleFile.getName() + " parsing error!");
                continue;
            } finally {
                scheduleFile.delete();
            }
        }
        return true;
    }
}
